import sourceMap from 'source-map-js';
import { useSourcemapInfo } from '../stores/sourcemapInfo';
const getSourceMap = async (url) => {
  console.log(url, 'map文件路径');

  return fetch(url, {
    method: 'POST',
  })
    .then((res) => {
      if (!res.ok) {
        throw new Error(`HTTP error! Status: ${res.status}`);
      }
      // 将响应数据解析为 JSON
      return res.json();
    })
    .then((data) => {
      // 处理响应数据
      console.log(data, 'map文件内容');
      return data;
    });
};

const findCodeBySourceMap = async (stackFrame) => {
  const { setSourcemapInfo } = useSourcemapInfo();
  // 获取map文件
  const sourceData = await getSourceMap(stackFrame.fileName + '.map');

  // 解析sourceMap文件
  const consumer = await new sourceMap.SourceMapConsumer(sourceData);

  // 通过报错的位置查找对应的源文件的名称和报错行数
  const originalPosition = consumer.originalPositionFor({
    line: stackFrame.lineNumber,
    column: stackFrame.columnNumber || 0,
  });
  const code = consumer.sourceContentFor(originalPosition.source);

  setSourcemapInfo({
    code,
    line: originalPosition.line,
    column: originalPosition.column,
  });
};

export { findCodeBySourceMap };
